package com.clz.workorder.viewmodel

import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import androidx.databinding.ObservableField
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.*
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.luck.picture.lib.adapter.GridImageAdapter
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.vincent.videocompressor.VideoCompress
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class OrderFinishViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var orderNo=ObservableField<String>("")
    var orderResponsbility=ObservableField<String>("")
    var orderMaintain=ObservableField<String>("")
    var orderHelper=ObservableField<ArrayList<HandleWorkerRequestBean.Helper>>(ArrayList())
    var orderType=ObservableField<Int>(0)
    var ordermoney=ObservableField<String>("")
    var orderTime=ObservableField<String>("")
    var orderContent=ObservableField<String>("")
    var orderfamily=ObservableField<Boolean>()
    var orderCommon=ObservableField<Boolean>(true)
    val finishSuccessEvent:SingleLiveEvent<Void> = SingleLiveEvent()
    var helperClick:BindingCommand<Void> = BindingCommand(BindingAction {
        gethelpers()
    })
    var submitClick:BindingCommand<Void> = BindingCommand(BindingAction {
        submit()

    })

    val showHelpersEvent:SingleLiveEvent<Array<HandleWorkerRequestBean.Helper>> = SingleLiveEvent()
//    val startUploadEvent:SingleLiveEvent<Void> = SingleLiveEvent()
    val uploadImgEvent:SingleLiveEvent<UploadImgEventBean> = SingleLiveEvent()
    @SuppressLint("SimpleDateFormat")
    fun uploadImgAndVideo(fromIndex:Int, fileList:ArrayList<LocalMedia>, context: Context){
//        Thread.sleep(3000)
        if (fromIndex< fileList.size){
            fileList[fromIndex].imageState= GridImageAdapter.STATE_LOADING
            uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
            if (TextUtils.isEmpty(fileList[fromIndex].remotePath)){
                if (PictureMimeType.isHasVideo(fileList[fromIndex].mimeType)){
                    if (TextUtils.isEmpty(fileList[fromIndex].compressPath)){
                        var externalFilesDir=context.getExternalFilesDir(Environment.DIRECTORY_MOVIES)
                        var customFile= File(externalFilesDir,"cache")
                        if (!customFile.exists()) {
                            customFile.mkdirs();
                        }
                        var destPath=customFile.absolutePath+ File.separator + "VID_" + SimpleDateFormat(
                            "yyyyMMdd_HHmmss"
                        ).format(
                            Date()
                        ) + ".mp4"
                        VideoCompress.compressVideoLow(fileList[fromIndex].realPath,destPath,object :
                            VideoCompress.CompressListener {
                            override fun onStart() {
                                Log.e("ReportSubmitViewmodel","--------------------------onStart")
                            }

                            override fun onSuccess() {
                                dismissLoading()
                                fileList[fromIndex].compressPath=destPath
                                fileList[fromIndex].imageState= GridImageAdapter.STATE_LOADING
                                uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                                uploadImg(fromIndex,fileList,context)
                                Log.e("ReportSubmitViewmodel","--------------------------onSuccess")
                            }

                            override fun onFail() {
                                fileList[fromIndex].imageState= GridImageAdapter.STATE_FAIL
                                uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                                dismissLoading()
                                uploadImgAndVideo(fromIndex+1,fileList,context)
                                Log.e("ReportSubmitViewmodel","--------------------------onFail")
                            }

                            override fun onProgress(percent: Float) {
                                Log.e("ReportSubmitViewmodel","--------------------------百分之"+percent)
                            }

                        })
                    }else{
                        uploadImg(fromIndex,fileList,context)
                    }
                }else{
                    uploadImg(fromIndex,fileList,context)
                }
            }else{
                fileList[fromIndex].imageState= GridImageAdapter.STATE_NORMAL
                uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                uploadImgAndVideo(fromIndex+1,fileList,context)
            }
        }
    }
    fun uploadImg(fromIndex:Int, fileList:ArrayList<LocalMedia>, context: Context){

        model.uploadHeadImg("gongdan",fileList[fromIndex].compressPath,"")
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe{}
            .subscribe(object :ApiSubscriberHelper<BaseBean<ImgRspBean>>(){
                override fun onResult(t: BaseBean<ImgRspBean>) {
                    dismissLoading()
                    if (t.code==200){
                        fileList[fromIndex].remotePath= t.data!!.url
                        fileList[fromIndex].imageState= GridImageAdapter.STATE_NORMAL
                        uploadImgEvent.postValue(UploadImgEventBean(fromIndex,true,fileList))
                    }else{
                        showErrorToast(t.msg)
                        fileList[fromIndex].imageState= GridImageAdapter.STATE_FAIL
                        uploadImgEvent.postValue(UploadImgEventBean(fromIndex,false,fileList))
                    }
                    uploadImgAndVideo(fromIndex+1,fileList,context)
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                    fileList[fromIndex].imageState= GridImageAdapter.STATE_FAIL
                    uploadImgEvent.postValue(UploadImgEventBean(fromIndex,false,fileList))
                    uploadImgAndVideo(fromIndex+1,fileList,context)
                }

            })
    }
    var localFiles=ObservableField<ArrayList<LocalMedia>>(ArrayList())
    fun uploadImg(selectList: ArrayList<LocalMedia>){
        var tempIndex=0
        for (item in selectList){
            tempIndex=selectList.indexOf(item)
            model.uploadHeadImg(item.compressPath)
                .compose(RxThreadHelper.rxSchedulerHelper(this))
                .doOnSubscribe{showLoading()}
                .subscribe(object :ApiSubscriberHelper<BaseBean<ImgRspBean>>(){
                    override fun onResult(t: BaseBean<ImgRspBean>) {
                        dismissLoading()
                        if (t.code==200){
                            if (tempIndex==selectList.size-1){

                            }
//                            files.add(t.data?.url!!)
                        }else{
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }
    private fun submit(){
        if (localFiles.get()!=null&& localFiles.get()!!.isNotEmpty()){
            for (item in localFiles.get()!!){
                if (item.imageState== GridImageAdapter.STATE_LOADING ||item.imageState== GridImageAdapter.STATE_WAIT_LOADING){
                    showNormalToast("请等待图片上传完成")
                    return
                }
            }
        }
        if (TextUtils.isEmpty(orderContent.get())){
            showNormalToast("请填写事件描述！")
            return
        }
        if (TextUtils.isEmpty(ordermoney.get())){
            ordermoney.set("0")
        }
        if (TextUtils.isEmpty(orderTime.get())){
            orderTime.set("0")
        }
        var files=ArrayList<String>()
        if (localFiles.get()!=null&& localFiles.get()!!.isNotEmpty()){
            for (item in localFiles.get()!!){
                if (item.imageState!= GridImageAdapter.STATE_FAIL &&!TextUtils.isEmpty(item.remotePath)){
                    files.add(item.remotePath)
                }
            }
        }
        var wg= orderHelper.get()?.let { HandleWorkerRequestBean(orderContent.get().toString(),files, it,orderNo.get().toString(),
            ordermoney.get().toString().toDouble(),
            orderTime.get().toString().toDouble(),if (orderCommon.get()==true) 1 else 0) }
        if (wg != null) {
            model.handleWorkOrder(wg).compose(RxThreadHelper.rxSchedulerHelper(this))
                .doOnSubscribe { showLoading() }
                .subscribe(object :ApiSubscriberHelper<BaseBean<Any>>(){
                    override fun onResult(t: BaseBean<Any>) {
                        dismissLoading()
                        if (t.code==200){
                            finishSuccessEvent.call()
                        }else{
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }
                })
        }
    }
    private fun gethelpers() {
        if (model.getDeptId()==0){
            model.getUserDetailInfo().compose(RxThreadHelper.rxSchedulerHelper(this))
                .subscribe(object : ApiSubscriberHelper<UserInfoBean>(){
                    override fun onResult(t: UserInfoBean) {
                        if (t.code==200){
                            model.saveDeptId(t.user.deptId)
                            model.getUsersByDeptId(model.getAreaId(),model.getLoginCompanyId().toString(),t.user.deptId.toString())
                                .compose(RxThreadHelper.rxSchedulerHelper(this@OrderFinishViewModel))
                                .doOnSubscribe { showLoading() }
                                .subscribe(object : ApiSubscriberHelper<BaseBean<List<UserBean>>>() {
                                    override fun onResult(t: BaseBean<List<UserBean>>) {
                                        dismissLoading()
                                        if (t.code == 200) {
                                            var helpers=ArrayList<HandleWorkerRequestBean.Helper>()
                                            for (item in t.data!!){
                                                if (item.userName != orderMaintain.get()){
                                                    helpers.add(HandleWorkerRequestBean.Helper(item.userId.toInt(),item.userName))
                                                }
                                            }
                                            for (item in orderHelper.get()!!){
                                                val isInchoosed=isInChoosed(item,helpers)
                                                if (isInchoosed!=-1){
                                                    helpers.removeAt(isInchoosed)
                                                }
                                            }
                                            val h=helpers.toTypedArray()
                                            showHelpersEvent.postValue(h)
                                        } else {
                                            showErrorToast(t.msg)
                                        }
                                    }

                                    override fun onFailed(msg: String?) {
                                        dismissLoading()
                                        showErrorToast(msg)
                                    }

                                })
                        }
                    }

                    override fun onFailed(msg: String?) {

                    }

                })
        }else{

            model.getUsersByDeptId(model.getAreaId(),model.getLoginCompanyId().toString(),model.getDeptId().toString())
                .compose(RxThreadHelper.rxSchedulerHelper(this@OrderFinishViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<List<UserBean>>>() {
                    override fun onResult(t: BaseBean<List<UserBean>>) {
                        dismissLoading()
                        if (t.code == 200) {
                            var helpers=ArrayList<HandleWorkerRequestBean.Helper>()
                            for (item in t.data!!){
                                if (item.userName != orderMaintain.get()){
                                    helpers.add(HandleWorkerRequestBean.Helper(item.userId.toInt(),item.userName))
                                }
                            }
                            for (item in orderHelper.get()!!){
                                val isInchoosed=isInChoosed(item,helpers)
                                if (isInchoosed!=-1){
                                    helpers.removeAt(isInchoosed)
                                }
                            }
                            val h=helpers.toTypedArray()
                            showHelpersEvent.postValue(h)
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }
    fun isInChoosed(i:HandleWorkerRequestBean.Helper,list:List<HandleWorkerRequestBean.Helper>):Int{
        for (item in list){
            if (i.id==item.id){
                return list.indexOf(item)
            }
        }
        return -1
    }

    public fun reportContentLength(content:String): String {
        return content.length.toString()+"/150"
    }
    fun helpersCount(helpers:ArrayList<HandleWorkerRequestBean.Helper>):Boolean{
        if (helpers.size>=2){
            return false
        }
        return true
    }
    }